#include<iostream>
#include<unistd.h>
//#include <string.h>
#include<cstring>
#include<cerrno>
#include<cassert>
#include<cstdlib>
#include<sys/wait.h>
#include<sys/types.h>
int main()
{
    //利用fork让两个不的进程看到同一份资源
    int pipefd[2] = {0};
    //1.创建匿名管道
    int n = pipe(pipefd);
    if(n<0)   //创建管道失败
    {
        std::cout<<"pipe error, "<<errno<<" : "<<strerror(errno)<<std::endl;
        return 1;
    }

    std::cout<<"pipefd[0]: "<<pipefd[0]<<std::endl;    //0读端
    std::cout<<"pipefd[1]: "<<pipefd[1]<<std::endl;   //1写端
    
    //2.  创建子进程
    pid_t id = fork();
    assert(id!=-1);

    if(id == 0)  //子进程
    {
        //3.关掉不需要得fd，实现让父进程读，子进程写得功能
        close(pipefd[0]);

        //4.开始通信 --结合某种场景
        int cnt = 0;
        while(true)
        {
            char x = 'X';
            write(pipefd[1],&x,1);
            std::cout<<"Cnt: "<<cnt++<<std::endl;
            sleep(1);
        }

        close(pipefd[1]);
        exit(0);
    }


    //父进程
    //3. 关闭不需要的fd，让父进程读，子进程写
    close(pipefd[1]);

    //4.开始通信
    char buffer[1024];
    int cnt = 0;
    while(true)
    {
        int n = read(pipefd[0], buffer, sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]='\0';
            std::cout<<"我是父进程，child give me messages:"<<buffer<<std::endl;
        }
        else if(n==0)
        {
            std::cout<<"我是父进程，读到了文件结尾"<<std::endl;
            break;
        }
        else{
            std::cout<<"我是父进程，读管道异常"<<std::endl;
            break;
        }
        sleep(2);
        if(cnt++>5) break;
    }

    close(pipefd[0]);


    int status = 0;
    waitpid(id, &status, 0);
    std::cout<<" sig: "<<(status &0x7f) << std::endl;
    


    sleep(20);



    return 0;
}